#!/usr/bin/python
# -*- coding: utf-8 -*-


'''
Created on 2013-6-25

@author: lyj
'''


import sys
import time
from bsddb import db
from threading import Thread
from threading import currentThread

database_folder = r'l:\_DevProject.Aptana3\demobsddb'

def the_callback_thread(lock_type):
    if sys.version_info[0] < 3:
        name = currentThread().getName()
    else:
        name = currentThread().name
        
    if lock_type == db.DB_LOCK_WRITE:
        lt = 'write'
    else:
        lt = 'read'
        
    an_id = env.lock_id()
    print "%s: locker ID: %s" % (name, an_id)
    
    # 第二个参数不能用an_id?
    lock = env.lock_get(an_id, None, lock_type)
    print "%s: Aquired %s lock: %s" % (name, lt, lock)
    
    if lt == 'write':
        # 测试阻塞
        time.sleep(10)
        
    env.lock_put(lock)
    print "%s: Released %s lock: %s" % (name, lt, lock)
    
    env.lock_id_free(an_id)
     

# 打印版本
print db.DB_VERSION_STRING
# 初始化数据库环境(DBEnv)
env = db.DBEnv()
# 打开数据库环境
# http://docs.oracle.com/cd/E17076_03/html/api_reference/CXX/frame_main.html
env.open(database_folder, db.DB_THREAD | db.DB_INIT_MPOOL | db.DB_INIT_LOCK | db.DB_CREATE)

threads = []
thread_1 = Thread(target=the_callback_thread,
                  args=(db.DB_LOCK_WRITE,) 
                  )
thread_2 = Thread(target=the_callback_thread,
                  args=(db.DB_LOCK_WRITE,) 
                  )
thread_3 = Thread(target=the_callback_thread,
                  args=(db.DB_LOCK_READ,) 
                  )
thread_4 = Thread(target=the_callback_thread,
                  args=(db.DB_LOCK_READ,) 
                  )
threads.append(thread_1)
threads.append(thread_2)
threads.append(thread_3)
threads.append(thread_4)

for t in threads:
    if sys.version_info[0] < 3:
        t.setDaemon(True)
    else:
        t.daemon = True
    t.start()
for t in threads:
    t.join()
